package cn.jy.nvr.downfile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jy.nvr.HCNetSDK;
import cn.jy.nvr.domain.DownloadItem;
import cn.jy.nvr.mapper.DonorMapper;
import cn.jy.nvr.utils.ConvertCopyUtils;

import com.sun.jna.NativeLong;
import com.sun.jna.ptr.IntByReference;
@Service
public class DownFile {
	static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE;
    HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo;//设备信息
    HCNetSDK.NET_DVR_IPPARACFG  m_strIpparaCfg;//IP参数
    HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo;//用户参数
    NativeLong lUserID;//用户句柄
    @Autowired
	DonorMapper donorMapper;
    Logger logger=Logger.getLogger(DownFile.class);
    private static Properties prop;
    	 private DownFile() {}
         private static DownFile downFile =new DownFile();
         public static DownFile getInstance(){
			return downFile;
		}
         
		public  NativeLong initAndLogin() {
    		 boolean initSuc = hCNetSDK.NET_DVR_Init();
    		 if (initSuc != true)
    	        {
    	           System.out.println("初始化失败");
    	        }
    		    m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30();
    		    prop = new Properties();
    		    try {
					prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("connectNvrConf.properties"));
				} catch (IOException e) {
					e.printStackTrace();
				}
    		    Short short1=new Short(prop.getProperty("port"));
    			lUserID = hCNetSDK.NET_DVR_Login_V30(prop.getProperty("IP"),short1 ,
    					 prop.getProperty("username"), prop.getProperty("password"), m_strDeviceInfo);
    			long userID = lUserID.longValue();
    			if(userID==-1){
    				System.out.println("登录失败");
    			}else{
    				System.out.println("成功登录NVR");
    			}
			return lUserID;
		}
    	
		public  void downFileByTime(final DownloadItem downloadItem ) {
			long iChannelNum=downloadItem.getChannel();
			NativeLong lChannel =new NativeLong(iChannelNum);
			Date startDate = null;
			Date endDate = null;
			Calendar starttime=Calendar.getInstance();
			 try {
				  startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(downloadItem.getStart());
				  starttime.setTime(startDate);
			} catch (ParseException e) {
				e.printStackTrace();
			} 
			 
			HCNetSDK.NET_DVR_TIME lpStartTime = new HCNetSDK.NET_DVR_TIME();
			lpStartTime.dwYear=starttime.get(Calendar.YEAR);
			lpStartTime.dwMonth=(starttime.get(Calendar.MONTH) + 1) ;
			lpStartTime.dwDay=starttime.get(Calendar.DAY_OF_MONTH);
			lpStartTime.dwHour=starttime.get(Calendar.HOUR_OF_DAY);
			lpStartTime.dwMinute=starttime.get(Calendar.MINUTE);
			lpStartTime.dwSecond=starttime.get(Calendar.SECOND);
			
			Calendar endtime=Calendar.getInstance();
			try {
				endDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(downloadItem.getEnd());
				endtime.setTime(endDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			HCNetSDK.NET_DVR_TIME lpStopTime=new HCNetSDK.NET_DVR_TIME() ;
			lpStopTime.dwYear=endtime.get(Calendar.YEAR);
			lpStopTime.dwMonth=(endtime.get(Calendar.MONTH) + 1);
			lpStopTime.dwDay=endtime.get(Calendar.DAY_OF_MONTH);
			lpStopTime.dwHour=endtime.get(Calendar.HOUR_OF_DAY);
			lpStopTime.dwMinute=endtime.get(Calendar.MINUTE);
			lpStopTime.dwSecond=endtime.get(Calendar.SECOND);
			
			 final String hkfile=downloadItem.getFilepath()+downloadItem.getFilename()+".mp4";
			 final String mp4file= downloadItem.getFilepath()+downloadItem.getFilename()+"jy.mp4";
			 System.out.println(hkfile+"下载");
			 System.out.println(mp4file+"转码");
			 final NativeLong  m_lLoadHandle = hCNetSDK.NET_DVR_GetFileByTime(lUserID, lChannel, lpStartTime, lpStopTime, hkfile);
			System.out.println( m_lLoadHandle.intValue()+"下载返回值");
			if( m_lLoadHandle.intValue()>=0){
				  System.out.println("下载中");
				  hCNetSDK.NET_DVR_PlayBackControl( m_lLoadHandle, HCNetSDK.NET_DVR_PLAYSTART, 0, null);
				  
				  final Timer Downloadtimer = new Timer();//新建定时器
				  Downloadtimer.schedule(new TimerTask(){

					@Override
					public void run() {
						IntByReference nPos = new IntByReference(0);
				           hCNetSDK.NET_DVR_PlayBackControl(m_lLoadHandle, HCNetSDK.NET_DVR_PLAYGETPOS, 0, nPos);
				           if (nPos.getValue() > 100)
				           {
				        	   
				               hCNetSDK.NET_DVR_StopGetFile(m_lLoadHandle);
				               m_lLoadHandle.setValue(-1);
				               System.out.println("下载失败");
				               Downloadtimer.cancel();
				               System.out.println("由于网络原因或DVR忙,下载异常终止!");
				           }
				           System.out.println("-----------"+nPos.getValue());
				           if (nPos.getValue() ==100)
				           { 
				               hCNetSDK.NET_DVR_StopGetFile(m_lLoadHandle);
				               m_lLoadHandle.setValue(-1);
				               logger.info("下载完成"+hkfile);
				               ConvertCopyUtils.ConvertFileToMP4(hkfile, mp4file);
				               ConvertCopyUtils.deleteFile(hkfile, mp4file);
				               Downloadtimer.cancel();
				           }
					}
					  
				  }, 0, 5000);//0秒后开始响应函数
			}else{
				System.err.println("下载失败");
			}
		}
		
}
